package com.jus.player.widget.component;

import android.content.Context;
import android.os.Handler;
import android.util.AttributeSet;
import android.view.GestureDetector;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewConfiguration;
import android.view.animation.Animation;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.SeekBar;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

import com.jus.player.R;

import xyz.doikki.videoplayer.controller.ControlWrapper;
import xyz.doikki.videoplayer.controller.IControlComponent;
import xyz.doikki.videoplayer.player.VideoView;
import xyz.doikki.videoplayer.util.L;

public class FullScreenPlayerView extends FrameLayout implements IControlComponent {

    private final ImageView thumb;
    private final ImageView mPlayBtn;

    private ControlWrapper mControlWrapper;
    private final int mScaledTouchSlop;
    private int mStartX, mStartY;
    private boolean isLongPressed = false;
    private final Handler handler = new Handler(); // 用于更新进度条

    public FullScreenPlayerView(@NonNull Context context) {
        super(context);
    }

    public FullScreenPlayerView(@NonNull Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
    }

    public FullScreenPlayerView(@NonNull Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }

    {
        LayoutInflater.from(getContext()).inflate(R.layout.layout_full_screen_player_controller, this, true);
        thumb = findViewById(R.id.iv_thumb);
        mPlayBtn = findViewById(R.id.play_btn);
        TextView tvSpeedHint = findViewById(R.id.tvSpeedHint);
        SeekBar seekBar = findViewById(R.id.seekBar);

        // 初始化 GestureDetector
        GestureDetector gestureDetector = new GestureDetector(getContext(), new GestureDetector.SimpleOnGestureListener() {
            @Override
            public boolean onSingleTapUp(MotionEvent e) {
                if (mControlWrapper != null) {
                    mControlWrapper.togglePlay();
                }
                return true;
            }

            @Override
            public void onLongPress(MotionEvent e) {
                // 长按事件：加速播放
                isLongPressed = true;
                if (mControlWrapper != null) {
                    mControlWrapper.setSpeed(2.0f);
                    tvSpeedHint.setVisibility(View.VISIBLE);
                }
            }
        });

        // 设置触摸监听
        setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                // 将事件交给 GestureDetector 处理
                gestureDetector.onTouchEvent(event);
                // 监听 ACTION_UP 事件，取消长按后恢复播放速度
                if (event.getAction() == MotionEvent.ACTION_UP && isLongPressed) {
                    isLongPressed = false;
                    if (mControlWrapper != null) {
                        mControlWrapper.setSpeed(1.0f);
                        tvSpeedHint.setVisibility(View.GONE);
                    }
                }
                // 返回 true 表示消费事件
                return true;
            }
        });
        // 设置进度条监听
        seekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
                if (fromUser && mControlWrapper != null) {
                    // 用户拖动进度条时，跳转到指定位置
                    long duration = mControlWrapper.getDuration();
                    long targetPosition = (long) (duration * progress / 100.0);
                    mControlWrapper.seekTo(targetPosition);
                }
            }
            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {}
            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {}
        });

        // 更新进度条
        handler.postDelayed(new Runnable() {
            @Override
            public void run() {
                if (mControlWrapper != null && mControlWrapper.isPlaying()) {
                    long currentPosition = mControlWrapper.getCurrentPosition();
                    long duration = mControlWrapper.getDuration();
                    if (duration > 0) {
                        int progress = (int) (currentPosition * 100 / duration);
                        seekBar.setProgress(progress);
                    }
                }
                handler.postDelayed(this, 1000); // 每隔 1 秒更新一次
            }
        }, 1000);


        mScaledTouchSlop = ViewConfiguration.get(getContext()).getScaledTouchSlop();
    }

    /**
     * 解决点击和VerticalViewPager滑动冲突问题
     */
    @Override
    public boolean onTouchEvent(MotionEvent event) {
        int action = event.getAction();
        switch (action) {
            case MotionEvent.ACTION_DOWN:
                mStartX = (int) event.getX();
                mStartY = (int) event.getY();
                return true;
            case MotionEvent.ACTION_UP:
                int endX = (int) event.getX();
                int endY = (int) event.getY();
                if (Math.abs(endX - mStartX) < mScaledTouchSlop
                        && Math.abs(endY - mStartY) < mScaledTouchSlop) {
                    performClick();
                }
                break;
        }
        return false;
    }

    @Override
    public void attach(@NonNull ControlWrapper controlWrapper) {
        mControlWrapper = controlWrapper;
    }

    @Override
    public View getView() {
        return this;
    }

    @Override
    public void onVisibilityChanged(boolean isVisible, Animation anim) {

    }

    @Override
    public void onPlayStateChanged(int playState) {
        switch (playState) {
            case VideoView.STATE_IDLE:
                L.e("STATE_IDLE " + hashCode());
                thumb.setVisibility(VISIBLE);
                break;
            case VideoView.STATE_PLAYING:
                L.e("STATE_PLAYING " + hashCode());
                thumb.setVisibility(GONE);
                mPlayBtn.setVisibility(GONE);
                break;
            case VideoView.STATE_PAUSED:
                L.e("STATE_PAUSED " + hashCode());
                thumb.setVisibility(GONE);
                mPlayBtn.setVisibility(VISIBLE);
                break;
            case VideoView.STATE_PREPARED:
                L.e("STATE_PREPARED " + hashCode());
                break;
            case VideoView.STATE_ERROR:
                L.e("STATE_ERROR " + hashCode());
                Toast.makeText(getContext(), R.string.dkplayer_error_message, Toast.LENGTH_SHORT).show();
                break;
            case VideoView.STATE_PLAYBACK_COMPLETED:
                mPlayBtn.setVisibility(VISIBLE);
                thumb.setVisibility(GONE);
                break;
        }
    }

    @Override
    public void onPlayerStateChanged(int playerState) {

    }

    @Override
    public void setProgress(int duration, int position) {

    }

    @Override
    public void onLockStateChanged(boolean isLocked) {

    }

    public void release() {
        // 1. 移除Handler回调
        handler.removeCallbacksAndMessages(null);

        // 2. 释放封面图资源
        if (thumb != null) {
            thumb.setImageDrawable(null);
        }

        // 3. 释放ControlWrapper（关键）
        if (mControlWrapper != null) {
            mControlWrapper.release();
            mControlWrapper = null;
        }
    }
}
